﻿using Microsoft.AspNetCore.Http;

namespace Service.Base
{
    public class UnitOfWorkService : IUnitOfWorkService
    {
        private readonly IHttpContextAccessor _HttpContext;
        private readonly ISqlSugarClient _DbContext;
        private readonly IRedisService _Redis;
        private readonly IResultHelperService _ResultHelper;
        private readonly IEnumHelperService _Enum;
        private readonly IOptions<JwtConfig> _Config;

        public UnitOfWorkService(IOptions<JwtConfig> con, IEnumHelperService en, IHttpContextAccessor httpContext, ISqlSugarClient db, IRedisService redis, IResultHelperService resultHelper)
        {
            _DbContext = db;
            _HttpContext = httpContext;
            _Redis = redis;
            _Enum = en;
            _Config = con;
            _ResultHelper = resultHelper;
        }

        public IEnumHelperService GetEnumHelper()
        {
            _Enum.SetTenant(GetTenantKey());
            return _Enum;
        }

        public string GetTenantKey()
        {
            var tenant = AppSettings.GetConfig("Tenant");

            var isfire = AppSettings.GetConfig("isfire") ?? "false";

            if (!isfire.ToBool())
            {
                var lang = _HttpContext.HttpContext.Request?.Headers?["Lang"].ToString();
                if (!string.IsNullOrEmpty(lang))
                {
                    if (lang == "en")
                    {
                        tenant = "en";
                    }
                    else if (lang == "zh-TW")
                    {
                        tenant = "tw";
                    }
                }
            }

            return tenant;
        }

        public ISqlSugarClient GetDbContext()
        {
            return _DbContext;
        }

        public IRedisService GetRedisConn()
        {
            _Redis.SetTenantKey(GetTenantKey());
            return _Redis;
        }

        public IResultHelperService GetResultHeplper()
        {
            _ResultHelper.SetRedisService(GetRedisConn());
            return _ResultHelper;
        }

        public string GetAdminJwt()
        {
            return _HttpContext.HttpContext.User.FindFirst(_Config.Value.AdminJwtKey)?.Value;
        }

        public string GetCustomerJwt()
        {
            return _HttpContext.HttpContext.User.FindFirst(_Config.Value.CustomerJwtKey)?.Value;
        }
    }
}